﻿using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1
{
    [Transaction(TransactionMode.Manual)]
    [Regeneration(RegenerationOption.Manual)]
    class Class1 : IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                ExecuteEventHandler executeEventHandler = new ExecuteEventHandler("Creat Model Line");
                ExternalEvent externalEvent = ExternalEvent.Create(executeEventHandler);

                // show UI
                MainWindow modelessView = new MainWindow(executeEventHandler, externalEvent);

                //窗口一直显示在主程序之前
                System.Windows.Interop.WindowInteropHelper mainUI = new System.Windows.Interop.WindowInteropHelper(modelessView);
                mainUI.Owner = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
                modelessView.Show();

                return Autodesk.Revit.UI.Result.Succeeded;
            }

            catch (Exception e)
            {
                message = e.Message;

                return Autodesk.Revit.UI.Result.Failed;
            }
        }
    }

    public class ExecuteEventHandler : IExternalEventHandler
    {
        public string Name { get; private set; }

        public Action<UIApplication> ExecuteAction { get; set; }

        public ExecuteEventHandler(string name)
        {
            Name = name;
        }

        public void Execute(UIApplication app)
        {
            if (ExecuteAction != null)
            {
                try
                {
                    ExecuteAction(app);
                }
                catch
                { }
            }
        }

        public string GetName()
        {
            return Name;
        }
    }
}
